package com.payment.controller.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.payment.entity.common.UserOrderPackage;
import com.payment.entity.common.UserOrderPayment;
import com.payment.entity.newrequestnotify.request.RequestNotify;
import com.payment.entity.newrequestnotify.response.ResponseNotify;
import com.payment.entity.payresults.callback.request.CallbackRequest;
import com.payment.entity.payresults.callback.request.CallbackRequestData;
import com.payment.entity.payresults.callback.request.CallbackRequestTradeData;
import com.payment.entity.payresults.callback.response.CallbackResponse;
import com.payment.entity.payresults.callback.response.CallbackResponseData;
import com.payment.service.PartnerService;
import com.payment.service.SequenceService;
import com.payment.service.UserOrderPackageService;
import com.payment.service.UserOrderPaymentService;
import com.payment.utils.Constant;
import com.payment.utils.HttpUtil;
import com.payment.utils.Md5Encrypt;
import com.payment.utils.UtilsInterfacesPackage;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@Api(description = "2.0:客户自行支付之后结果回调接口")

/**
 * 1，客户自行支付之后将结果回传给领科的接口：
 *
 * 2，相同的接口在1.0时接口地址是：pay/callback
 *
 * 3，更新的数据表为：user_order_package_t，user_order_payment_t ；
 *
 *  4，更新的数据库为：v-shop
 *
 *  5，此接口还暂未使用
 *
 * @author lm
 * @date 2019/5/24
 */

public class CallbackController {

    private static Logger logger = Logger.getLogger(CallbackController.class);
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private PartnerService partnerService;
    @Autowired
    private UserOrderPackageService orderService;
    @Autowired
    private UserOrderPaymentService paymentService;

    /*支付方式:1-微信支付，2-paypal支付，3-oceanpay支付,0-第三方自行支付*/
    /*收款账户：2-B端客户；1-领科账户*/

    @PostMapping(value = "callback", produces = "application/json;charset=utf-8")
    @CrossOrigin
    public String paymentResultCallback(@RequestBody CallbackRequest request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3，定义回报报文
        String jsonString;
        try {
            UtilsInterfacesPackage utils = new UtilsInterfacesPackage();
            String reStr = JSON.toJSONString(request);
            if (reStr == null) {
                logger.debug("请求报文不合法:requestStr为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                logger.debug("前端请求报文是：" + reStr);
                CallbackRequest requestPackage = JSONArray.parseObject(reStr, CallbackRequest.class);
                String requestSign = requestPackage.getSign();
                if (requestSign == null) {
                    logger.debug("请求报文不合法:sign为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    logger.debug("请求的签名是：" + requestSign);
                    CallbackRequestData requestData = requestPackage.getData();
                    if (requestData == null) {
                        logger.debug("请求报文不合法:data为空");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {

                        String partnerCode = requestData.getPartnerCode();
                        String ConnSeqNo = requestData.getConnSeqNo();
                        String tradeTime = requestData.getTradeTime();
                        String tradeType = requestData.getTradeType();
                        String version = requestData.getVersion();
                        String lang = requestData.getLang();


                        if (requestData.getTradeData() == null || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType)) {
                            logger.debug("请求报文不合法:data参数不合法");
                            jsonString = utils.dataWeiKong(connSeqNo, curtime);
                            return jsonString;
                        } else {

                            CallbackRequestTradeData requestTradeData = requestData.getTradeData();
                            String orderId = requestTradeData.getOrderId();
                            String paymentStatus = requestTradeData.getPaymentStatus();
                            String paymentAmount = requestTradeData.getPaymentAmount();
                            String paymentCurrency = requestTradeData.getPaymentCurrency();
                            String requestOrderId = requestTradeData.getRequestOrderId();

                            if (StringUtils.isBlank(orderId) || StringUtils.isBlank(paymentStatus) || StringUtils.isBlank(paymentAmount) || StringUtils.isBlank(paymentCurrency) || StringUtils.isBlank(requestOrderId)) {
                                logger.debug("请求报文不合法:orderId和amount不能为空！");
                                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                                return jsonString;
                            } else {
                                // 将请求体json转成String
                                String str = JSON.toJSONString(requestData);
                                // 将Str拿去计算签名
                                String sign = utils.calculateSignature(str);
                                logger.debug("计算的签名是：" + sign);

                                if (!requestSign.equalsIgnoreCase(sign)) {
                                    logger.debug("签名失败！");
                                    jsonString = utils.signatureFailure(ConnSeqNo, partnerCode, tradeTime, tradeType);
                                    return jsonString;
                                } else {//把传回来的数据入库

                                    if (!paymentStatus.equalsIgnoreCase("success")) {
                                        logger.debug("paymentStatus状态不成功：" + paymentStatus);
                                        jsonString = utils.unsuccessfulStatusData(ConnSeqNo, partnerCode, tradeTime, tradeType);
                                        return jsonString;

                                    } else {
                                        int c = orderService.findOrderIdByNotify(orderId);

                                        if (c <= 0) {

                                            // 成功的回调数据入库：根据支付id和金额入库：user_order_package_t
                                            UserOrderPackage order = new UserOrderPackage();
                                            order.setRequestOrderId(requestOrderId);
                                            order.setOrderId(orderId);
                                            order.setPayCurrency(paymentCurrency);
                                            order.setPayAmount(paymentAmount);
                                            order.setPayType(Constant.PAY_QITA);
                                            order.setPayRst("success");
                                            order.setIsNotify("1");
                                            order.setPayAccount("2");
                                            order.setPayStatus("1");
                                            order.setPayResultDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                                            orderService.updateCallbackPayRst(order);

                                            //成功的回调数据入库：根据支付id和金额入库：user_order_payment_t
                                            UserOrderPayment payment = new UserOrderPayment();
                                            payment.setRequestOrderId(requestOrderId);
                                            payment.setPayCurrency(paymentCurrency);
                                            payment.setPayAmount(paymentAmount);
                                            payment.setPayType(Constant.PAY_QITA);
                                            payment.setPayRst("success");
                                            paymentService.updateCallbackPayRst(payment);


                                            List<UserOrderPackage> userOrderList = orderService.queryOrderByOrderIdAndAmount(orderId, paymentAmount);

                                            if (userOrderList != null && !userOrderList.isEmpty()) {

                                                for (UserOrderPackage u : userOrderList) {

                                                    String deviceId = u.getDeviceCode();
                                                    String Amount = u.getPayAmount();
                                                    String secret = partnerService.findSecretByPartnerCode(partnerCode);

                                                    logger.debug("查询到的订单orderId是:" + orderId + ";DeviceId是:" + deviceId + ";payAmount是：" + Amount + ";密钥是：" + secret);

                                                    RequestNotify notify = new RequestNotify();
                                                    notify.setDeviceId(deviceId);
                                                    notify.setOrderId(orderId);
                                                    notify.setPayAmount(Amount);
                                                    notify.setPayType(Constant.PAY_QITA);
                                                    notify.setSecret(secret);
                                                    notify.setPartnerCode(partnerCode);
                                                    // 开始组装json
                                                    String requestStr = JSON.toJSONString(notify);
                                                    logger.debug("请求北京的接口请求报文：" + requestStr);
                                                    String url = Constant.requestURI + Constant.iot_notify;
                                                    // 发送post请求，并接收返回结果
                                                    String returnStr = HttpUtil.httpPost(url, requestStr);
                                                    logger.debug("北京回复的下发接口响应报文：" + returnStr);
                                                    ResponseNotify re = JSONArray.parseObject(returnStr, ResponseNotify.class);

                                                    String retCode = re.getRetCode();

                                                    if (re != null) {

                                                        if (true == Constant.RET_CODE_0000.equalsIgnoreCase(retCode) || true == Constant.RET_CODE_0113.equalsIgnoreCase(retCode)) {
                                                            UserOrderPackage user = new UserOrderPackage();
                                                            user.setOrderId(orderId);
                                                            user.setIsNotify("0");
                                                            orderService.updateCallbackIsNotify(user);
                                                            logger.debug("同步-成功");
                                                        } else {
                                                            logger.debug("同步不成功");
                                                            return null;
                                                        }
                                                    } else {
                                                        logger.debug("同步异常");
                                                        return null;
                                                    }


                                                }

                                            } else {
                                                logger.debug("无需要去做支付结果通知的数据");
                                                return null;
                                            }

                                            //给前端回传：
                                            CallbackResponseData data = new CallbackResponseData();
                                            data.setConnSeqNo(ConnSeqNo);
                                            data.setPartnerCode(partnerCode);
                                            data.setTradeType(tradeType);
                                            data.setTradeTime(tradeTime);
                                            data.setRetCode("0000");
                                            data.setRetMsg("成功");

                                            CallbackResponse response = new CallbackResponse();
                                            response.setData(data);
                                            response.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));
                                            // 返回给调用者的报文
                                            jsonString = JSON.toJSONString(response);
                                            logger.debug("响应报文：" + jsonString);
                                            return jsonString;


                                        } else {
                                            jsonString = utils.repeatedReturn(ConnSeqNo, partnerCode, tradeTime, tradeType);
                                            return jsonString;
                                        }

                                    }


                                }
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
